package com.lcq.gulimall.product.exception;

import com.lcq.common.exception.BizCodeEnum;
import com.lcq.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.lcq.gulimall.product.controller")
public class ExceptionControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler(MethodArgumentNotValidException e){
        BindingResult br = e.getBindingResult();
        Map map = new HashMap();
        if(br.hasErrors()){
            br.getFieldErrors().forEach((item)->{
                map.put(item.getField(),item.getDefaultMessage());
            });
        }
        return R.error(BizCodeEnum.INVALID_EXCEPTION.getCode(),BizCodeEnum.INVALID_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R exceptionHandler(HttpMessageNotReadableException e){
        return R.error(BizCodeEnum.PARAM_NOT_READABLE_EXCEPTION.getCode(),BizCodeEnum.PARAM_NOT_READABLE_EXCEPTION.getMsg()).put("data",e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e){
        e.printStackTrace();
        return R.error(BizCodeEnum.UNKNOW_EXEPTION.getCode(),BizCodeEnum.UNKNOW_EXEPTION.getMsg()).put("data",e.getMessage());
    }
}
